<script setup>
import {ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

// const TableData = ref([])

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
  // tableData: {
  //   type: Array,
  //   default: () => [],
  //   required: true
  // },
})

const personList = ref([])

const initPersonListData = async () => {
  try {
    const res = await requestUtil.post('monitor_alert/person/list')
    const data = res.data
    if (data.code === 200) {
      console.log(data.msg, '---------------------')
      personList.value = data.msg;
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}


const form = ref({
  id: -1,
  name: '',
  remark: '',
  personListData: [],
})

const checkGroupName = async (rule, value, callback) => {
  if (!value) return callback(new Error('联系人不能为空')) // 优先检查空值

  // 仅在新增模式时校验
  if (props.id === -1) {  // 使用props.id判断模式
    try {
      const res = await requestUtil.post('monitor_alert/group/check', {name: value})
      const data = res.data
      if (data.code === 500) {
        callback(new Error(data.msg))
      } else {
        callback()
      }
    } catch (e) {
      console.log(e)
      callback(new Error('校验服务异常'))
    }
  } else {
    callback()
  }
}

const rules = ref({
  name: [
    {required: true, message: '分组名称不能为空', trigger: 'blur'},
    {validator: checkGroupName, trigger: 'blur'}
  ],
})

const formRef = ref(null)

const initFormData = async (id) => {
  try {
    const res = await requestUtil.get('monitor_alert/alert/group/action?id=' + id)
    let data = res.data;
    if (data.code === 200) {
      form.value = res.data.msg
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

const emits = defineEmits(['update:modelValue', 'initTableData'])

const handleClose = () => {
  formRef.value.resetFields()
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    try {
      if (valid) {
        console.log(form.value, '------------form.value')
        let res = await requestUtil.post('monitor_alert/alert/group/action', form.value);
        let data = res.data;
        if (data.code === 200) {
          ElMessage.success('执行成功')
          formRef.value.resetFields()
          emits('initTableData')
          handleClose()
        } else {
          ElMessage.error(data.msg)
        }
      } else {
        console.log('fail')
      }
    } catch (error) {
      console.error('Error fetching table data:', error)
      ElMessage.error('请求失败，请稍后再试')
    }
  })
}

watch(
    () => props.dialogVisible,
    () => {
      let id = props.id;
      console.log(props.id, '-----------')
      // TableData.value = props.tableData;
      initPersonListData()
      if (id !== -1) {
        initFormData(id);
      } else {
        form.value = {
          id: -1,
          name: '',
          remark: '',
          personListData: [],
        }
      }
    }
)
</script>

<template>
  <el-dialog
      model-value="dialogVisible"
      :title="dialogTitle"
      style="padding: 40px"
      width="700px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="组名称:" prop="name">
        <el-input v-model="form.name" placeholder="请输入联系组名"></el-input>
      </el-form-item>

      <el-form-item label="描述:" prop="remark">
        <el-input type="textarea" v-model="form.remark" placeholder="请输入描述"></el-input>
      </el-form-item>

      <el-form-item label="选择联系人:" prop="personList">
        <el-select
            multiple
            v-model="form.personListData"
            placeholder="请选择告警联系人"
        >
          <el-option v-for="item in personList" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>